#include"TcpServer.hpp"
#include"Protocol.hpp"
#include"MyDaemon.hpp"

#include<iostream>
#include<memory>
#include<signal.h>
using namespace bobo;

static Response __calculate(const Request& req)
{
    Response res;
    switch(req._op)
    {
        case '+':
            res._result = req._x + req._y;
            break;
        case '-':
            res._result = req._x - req._y;
            break;
        case '*':
            res._result = req._x * req._y;
            break;
        case '/':
            if(req._y == 0) res._code = 1;
            else res._result = req._x / req._y;
            break;
        case '%':
            if(req._y == 0) res._code = 2;
            else res._result = req._x % req._y;
            break;
        default:
            res._code = 3;
            break;       
    }

    return res;
}
void calculate(int sock)
{
    std::string inbuffer;
    while (true)
    {
        // 1. 读取成功
        bool res = Recv(sock, &inbuffer); // 在这里我们读到了一个请求？
        if (!res) break;
        // 2. 
        std::string package = Decode(inbuffer);
        if(package.empty()) continue; 
        // 4. 反序列化，字节流 -> 结构化
        Request req;
        req.Deserialize(package); // 反序列化
        // 5. 业务逻辑
        Response resp = __calculate(req);
        // 6. 序列化
        std::string respString = resp.Serialize(); 
        package = Encode(respString);
        Send(sock, package);
    }
}

void usage(const char* message)
{
    std::cout << "Usage: " << message << "ip" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        usage(argv[0]);
        exit(-1);
    }
    
    myDaemon(); // 守护进程

    uint16_t port = atoi(argv[1]);
    std::unique_ptr<TcpServer> svr(new TcpServer(port));
    svr->BindService(calculate);
    svr->Start();

    return 0;
}